package com.xjtu.platform.security.forgetpassword;

import com.xjtu.platform.common.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.xjtu.platform.common.Result.ERR_CODE_BUSINESS;
import static com.xjtu.platform.common.Utils.sendMail;

@RestController
@RequestMapping("/security/forgetpassword")
public class ForgetPasswordAPI {
    @Resource
    ForgetPasswordService forgetPasswordService;

    @PostMapping("/checkUser")
    public Result Check(@RequestBody ForgetPasswordDto dto) {

        boolean ok = forgetPasswordService.checkUser(dto);
        if (ok) {
            return Result.success();
        } else {
            return Result.fail(ERR_CODE_BUSINESS, " 用户不存在");
        }
    }

    @PostMapping("/getEmail")
    public Result getEmail(@RequestBody ForgetPasswordDto dto) {


        return (Result.success(forgetPasswordService.getEmail(dto)));
    }


    @PostMapping("/sendEmail")
    public Result sendEmail(@RequestBody ForgetPasswordDto dto) throws Exception {
        String user_id = dto.getUser_id();
//        String code = forgetPasswordService.findConde(dto);
//        String code = forgetPasswordService.getRedisValue(user_id);

        System.out.println("无验证码");
        String newCode = forgetPasswordService.setRedisCode(user_id);
        dto.setCode(newCode);
//            forgetPasswordService.sendEmail(dto);

        sendMail(forgetPasswordService.getEmail(dto), "您的验证码为：" + newCode + "\n有限期为10分钟");

        System.out.println("验证码发送成功");
        return Result.success(
                "验证码发送成功"
        );

    }


    @PostMapping("/updatepwd")
    public Result updatePwd(@RequestBody ForgetPasswordDto dto) {

        System.out.println(dto.getCode());
        if (forgetPasswordService.updatePwd(dto)) {
            return Result.success("修改成功");
        } else {
            return Result.fail(ERR_CODE_BUSINESS, "验证码错误");
        }

    }

    @RequestMapping(value = "/redisTest", method = RequestMethod.POST)
    void Test(@RequestParam String user_id) throws InterruptedException {
        String code = forgetPasswordService.setRedisCode(user_id);
        System.out.println(code);
        Thread.sleep(12000);
        System.out.println(code.equals(forgetPasswordService.getRedisValue(user_id)));
    }
}
